<!-- 对 图片集 组件的编辑 -->
<template>
  <div class="images-edit" v-if="dialogShow">
    <SetDesignDialog :title="name" :dialogVisible="dialogShow" :close="close" :saveclose="saveclose"
      ref="settingComponentDialog">
      <div class="edit-container-u">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="设置" name="1">
            <el-row>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="每行列数" style="margin-bottom:0px;">
                    <el-select style="width:80px;" size="mini" v-model="data.config.column" placeholder="请选择">
                      <el-option label="2" :value="2"></el-option>
                      <el-option label="3" :value="3"></el-option>
                      <el-option label="4" :value="4"></el-option>
                      <el-option label="5" :value="5"></el-option>
                      <el-option label="6" :value="6"></el-option>
                      <el-option label="7" :value="7"></el-option>
                      <el-option label="8" :value="8"></el-option>
                      <el-option label="9" :value="9"></el-option>
                      <el-option label="10" :value="10"></el-option>
                      <el-option label="11" :value="11"></el-option>
                      <el-option label="12" :value="12"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="8">
                <PaddingTop :defValue="data.config.paddingTop" :chgValue="(d)=>{data.config.paddingTop = d}" />
              </el-col>
              <el-col :span="8">
                <PaddingBottom :defValue="data.config.paddingBottom" :chgValue="(d)=>{data.config.paddingBottom = d}" />
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="图片截断" style="margin-bottom:0px;">
                    <el-select style="width:160px;" size="mini" v-model="data.config.shape" placeholder="请选择">
                      <el-option label="非截断" :value="0"></el-option>
                      <el-option label="截断" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="外框比例" style="margin-bottom:0px;">
                    <el-select style="width:160px;" size="mini" v-model="data.config.outRatio" placeholder="请选择">
                      <el-option label="1:1" :value="'1:1'"></el-option>
                      <el-option label="4:3" :value="'4:3'"></el-option>
                      <el-option label="3:4" :value="'3:4'"></el-option>
                      <el-option label="2:3" :value="'2:3'"></el-option>
                      <el-option label="3:2" :value="'3:2'"></el-option>
                      <el-option label="16:9" :value="'16:9'"></el-option>
                      <el-option label="9:16" :value="'9:16'"></el-option>
                      <el-option label="3:1" :value="'3:1'"></el-option>
                      <el-option label="1:3" :value="'1:3'"></el-option>
                      <el-option label="5:2" :value="'5:2'"></el-option>
                      <el-option label="2:5" :value="'2:5'"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="内框比例" style="margin-bottom:0px;">
                    <el-select style="width:160px;" size="mini" v-model="data.config.inRatio" placeholder="请选择">
                      <el-option label="默认" :value="''"></el-option>
                      <el-option label="1:1" :value="'1:1'"></el-option>
                      <el-option label="4:3" :value="'4:3'"></el-option>
                      <el-option label="3:4" :value="'3:4'"></el-option>
                      <el-option label="2:3" :value="'2:3'"></el-option>
                      <el-option label="3:2" :value="'3:2'"></el-option>
                      <el-option label="16:9" :value="'16:9'"></el-option>
                      <el-option label="9:16" :value="'9:16'"></el-option>
                      <el-option label="3:1" :value="'3:1'"></el-option>
                      <el-option label="1:3" :value="'1:3'"></el-option>
                      <el-option label="5:2" :value="'5:2'"></el-option>
                      <el-option label="2:5" :value="'2:5'"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="图片间距" style="margin-bottom:0px;">
                    <el-select style="width: 100px;" size="mini" v-model="data.config.imageMargin" placeholder="请选择">
                      <el-option label="无间距" value=""></el-option>
                      <el-option label="1px" value="1px"></el-option>
                      <el-option label="2px" value="2px"></el-option>
                      <el-option label="3px" value="3px"></el-option>
                      <el-option label="4px" value="4px"></el-option>
                      <el-option label="5px" value="5px"></el-option>
                      <el-option label="6px" value="6px"></el-option>
                      <el-option label="7px" value="7px"></el-option>
                      <el-option label="8px" value="8px"></el-option>
                      <el-option label="9px" value="9px"></el-option>
                      <el-option label="10px" value="10px"></el-option>
                      <el-option label="12px" value="12px"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="图片内框距" style="margin-bottom:0px;">
                    <el-select style="width: 100px;" size="mini" v-model="data.config.imagePadding" placeholder="请选择">
                      <el-option label="无框距" value=""></el-option>
                      <el-option label="1px" value="1px"></el-option>
                      <el-option label="2px" value="2px"></el-option>
                      <el-option label="3px" value="3px"></el-option>
                      <el-option label="4px" value="4px"></el-option>
                      <el-option label="5px" value="5px"></el-option>
                      <el-option label="6px" value="6px"></el-option>
                      <el-option label="7px" value="7px"></el-option>
                      <el-option label="8px" value="8px"></el-option>
                      <el-option label="9px" value="9px"></el-option>
                      <el-option label="10px" value="10px"></el-option>
                      <el-option label="12px" value="12px"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="边框大小" style="margin-bottom:0px;">
                    <el-select style="width: 100px;" size="mini" v-model="data.config.borderWidth" placeholder="请选择">
                      <el-option label="无" value=""></el-option>
                      <el-option label="1px" value="1px"></el-option>
                      <el-option label="2px" value="2px"></el-option>
                      <el-option label="3px" value="3px"></el-option>
                      <el-option label="4px" value="4px"></el-option>
                      <el-option label="5px" value="5px"></el-option>
                      <el-option label="6px" value="6px"></el-option>
                      <el-option label="7px" value="7px"></el-option>
                      <el-option label="8px" value="8px"></el-option>
                      <el-option label="9px" value="9px"></el-option>
                      <el-option label="10px" value="10px"></el-option>
                      <el-option label="12px" value="12px"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth" @submit.native.prevent>
                  <el-form-item label="边框圆角" style="margin-bottom:0px;">
                    <el-input @blur="borRadiusblur" type="number" min="0" size="mini" v-model="data.config.borderRadius"
                      placeholder="0" style="width:70px;">
                    </el-input> px
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="边框颜色" style="margin-bottom:0px;">
                    <el-color-picker v-model="data.config.borderColor"></el-color-picker>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="8">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="懒加载" style="margin-bottom:0px;">
                    <el-select size="mini" style="width:100px;" v-model="data.config.islazyload" placeholder="请选择">
                      <el-option label="关闭" :value="0"></el-option>
                      <el-option label="开启" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row style="width:840px;">
              <el-col :span="16">
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="灯箱效果" style="margin-bottom:0px;">
                    <el-select style="width:160px;" size="mini" v-model="data.config.lightbox" placeholder="请选择">
                      <el-option label="无灯箱" :value="0"></el-option>
                      <el-option label="单图灯箱" :value="1"></el-option>
                      <el-option label="多图灯箱" :value="2"></el-option>
                    </el-select>
                    <span class="tip-color1">若灯箱开启，链接无效！</span>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="图片列表" name="2">
            <div class="imgList-u">
              <draggable v-model="data.imageList" class="imaged-placeholder" v-bind="{draggable:'.img-item-draggable'}"
                @end="datadragEnd">
                <div class="img-item img-item-draggable" v-for="(item, index) in data.imageList" :key="index">
                  <div class="image">
                    <el-image :fit="'scale-down'" :src="item.src"></el-image>
                  </div>
                  <div class="demonstration"><i @click.stop="editorLink(index)" class="el-icon-link"></i><i
                      @click.stop="editorAttr(index)" class="el-icon-edit"></i><i @click.stop="deleteImage(index)"
                      class="el-icon-delete"></i></div>
                </div>
                <div class="img-item" @click.stop="addImage" slot="header">
                  <div class="image" style="cursor:pointer;">
                    <el-image :src="ImagesPopAdd"></el-image>
                  </div>
                </div>
              </draggable>
            </div>
          </el-tab-pane>
          <el-tab-pane label="样式选择" name="3">
            <el-form label-width="80px" class="theme-uu">
              <el-form-item label="当前样式" style="margin-bottom:0px;">
                <el-select :disabled="true" size="mini" v-model="data.theme" placeholder="请选择" style="width:230px;">
                  <el-option v-for="(item, index) in themes" :key="index" :label="item.content" :value="''+item.theme">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div class="iframe" v-loading="iframeLoading">
              <iframe :src="iframeSrc" frameborder="0" style="width:100%;height:354px; height:calc(100vh - 300px);" ref="iframeRender"></iframe>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </SetDesignDialog>

    <ChooseRepertory ref="chooseImage" />
    <WDialogLink ref="wDialogLink" />
    <WDialogImageAttr ref="wDialogImageAttr" />
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import WDialogLink from '@/components/common/design/dialog/widgets/WDialogLink.vue'
import WDialogImageAttr from '@/components/common/design/dialog/widgets/WDialogImageAttr.vue'

import ChooseRepertory from '@/components/common/repertory/ChooseRepertory.vue'
// import ImagesEmpty from '@/assets/images/image-empty.png'
import ImagesPopAdd from '@/assets/images/pop_add.png'
import ImagesDefault from '@/assets/images/images_default.jpg'
import PaddingTop from '@/components/common/design/dialog/component/formitem/PaddingTop.vue'
import PaddingBottom from '@/components/common/design/dialog/component/formitem/PaddingBottom.vue'
import SetDesignDialog from '@/components/common/dialog/SetDesignDialog.vue'
import * as WindowType from '@/config/windowtype.js'
// import * as PubsubType from '@/config/pubsubtype.js'
import * as functions from '@/core/functions.js'
import VueFunctions from '@/core/VueFunctions.js'
import BackendjsFunctions from '@/core/BackendjsFunctions.js'
import { mapState } from 'vuex'
// import PubSub from 'pubsub-js'
// import Global from '@/config/global.js'
import qs from 'qs'
import _ from 'lodash'

export default {
  computed: {
    ...mapState([
      'design'
    ]),
    imageListLength () {
      return '图片数量：' + this.data.imageList.length
    }
  },
  created () {
    VueFunctions.method(WindowType.EDIT_COMPONENT_WITH_COMPONENTIMAGES, (bjComponent) => {
      this.close()
      this.dialogShow = true
      this.bjComponent = bjComponent
      this.data = bjComponent.render.data
      this.repertoryData = bjComponent._other.imageList

      this.data.theme = '' + this.data.theme

      // coding ...
      if (this.data && this.data.config && this.data.config.textAlign === '') {
        this.data.config.textAlign = 'left'
      }

      // 设置列数范围
      let column = this.data.config.column ? parseInt(this.data.config.column) : 2
      if (column < 2 || column > 12 || isNaN(column)) {
        column = 2
      }
      this.data.config.column = column

      this.activeName = '1'
      this.init = true
      this.iframeLoading = true

      this.iframeStyle = {
        w: 825,
        row: 7,
        col: 4,
        compname: 'component_images',
        theme: this.$store.state.site.config.theme,
        color: this.$store.state.site.config.color,
        ttextalign: 'center',
        tcolor: '#888',
        now: new Date().getTime()
      }
      let query = qs.stringify(this.iframeStyle)
      this.iframeSrc = '/api/udin/component?' + query

      this.$nextTick(() => {
        this.$refs['settingComponentDialog'].open()
      })

      // iframe 加载完成后回调的方法，
      let funcname = WindowType.API_UDIN_COMPONENT_ONLOAD_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
      window[funcname] = () => {
        this.iframeLoading = false
        let componentName = this.getComponentName()
        let defaultData = BackendjsFunctions.componentDefaultData(componentName)
        let objArray = []
        for (let i = 1; i <= this.themes.length; i++) {
          defaultData.ele = '#render-' + i

          let configTheme = this.themes.find(element => {
            return parseInt(element.theme) === i
          })
          defaultData.data.theme = configTheme.theme

          let imageList = [
            {
              src: ImagesDefault,
              title: '',
              alt: '',
              caption: configTheme ? configTheme.content : '文字标题',
              imglink: {
                href: '',
                target: '_blank'
              }
            }
          ]
          defaultData.data.imageList = imageList
          defaultData.data.config.column = 1

          objArray.push({
            renderData: _.cloneDeep(defaultData),
            title: '编号：' + i,
            theme: i
          })
          // objArray.push(_.cloneDeep(defaultData))
        }
        // 调用 iframe 中的 render 方法进行渲染
        this.$refs['iframeRender'].contentWindow.render(objArray, this.data.theme)
      }

      // 选择theme后回调的方法，并且传入选择的数据
      let funcallbackname = WindowType.API_UDIN_COMPONENT_ONLOAD_CALLBACK_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
      window[funcallbackname] = (renderData) => {
        this.data.theme = '' + renderData.data.theme
        if (this.init) {
          this.init = false
        }
        // 校验现在的theme是否与iframe显示的选择的theme一致
        this.$refs['iframeRender'].contentWindow.checkTheme(this.data.theme)
      }
    })
  },
  mounted () {
    // PubSub.subscribe(PubsubType.PUBSUB_DIGLOG_COMPONENT_CLOSE, (event, data) => {
    //   this.close()
    // })
    // PubSub.subscribe(PubsubType.PUBSUB_DIGLOG_COMPONENT_AND_CONTAINER_CLOSE, (event, data) => {
    //   this.close()
    // })
  },
  data () {
    return {
      dialogShow: false,
      iframeLoading: true,
      activeName: '1',
      iframeStyle: {},
      formLabelWidth: '120px',
      name: '图片集',
      bjComponent: null,
      data: null,
      repertoryData: [],
      iframeSrc: null,
      themes: themes,
      // 是否第一次进来
      init: true,
      // 是否第一次加载样式选择
      initiframe: true,
      // import 引入
      ImagesPopAdd: ImagesPopAdd,
      // 图片列表的总数
      total: 32
    }
  },
  methods: {
    // 标签切换触发
    handleClick (tab, event) {
      if (tab.name === '3' && this.initiframe) {
        this.initiframe = false
        this.iframeLoading = true
        this.iframeStyle = {
          w: 825,
          row: 7,
          col: 4,
          compname: 'component_images',
          theme: this.$store.state.site.config.theme,
          color: this.$store.state.site.config.color,
          ttextalign: 'center',
          tcolor: '#888',
          now: new Date().getTime()
        }
        let query = qs.stringify(this.iframeStyle)
        this.iframeSrc = '/api/udin/component?' + query

        this.$nextTick(() => {
          this.$refs['settingComponentDialog'].open()
        })

        // iframe 加载完成后回调的方法，
        let funcname = WindowType.API_UDIN_COMPONENT_ONLOAD_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
        window[funcname] = () => {
          this.iframeLoading = false
          let componentName = this.getComponentName()
          let defaultData = BackendjsFunctions.componentDefaultData(componentName)
          let objArray = []
          for (let i = 1; i <= this.themes.length; i++) {
            defaultData.ele = '#render-' + i

            let configTheme = this.themes.find(element => {
              return parseInt(element.theme) === i
            })
            defaultData.data.theme = configTheme.theme

            let imageList = [
              {
                src: ImagesDefault,
                title: '',
                alt: '',
                caption: configTheme ? configTheme.content : '文字标题',
                imglink: {
                  href: '',
                  target: '_blank'
                }
              }
            ]
            defaultData.data.imageList = imageList
            defaultData.data.config.column = 1

            objArray.push({
              renderData: _.cloneDeep(defaultData),
              title: '编号：' + i,
              theme: i
            })
            // objArray.push(_.cloneDeep(defaultData))
          }
          // 调用 iframe 中的 render 方法进行渲染
          this.$refs['iframeRender'].contentWindow.render(objArray, this.data.theme)
        }
        // 选择theme后回调的方法，并且传入选择的数据
        let funcallbackname = WindowType.API_UDIN_COMPONENT_ONLOAD_CALLBACK_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
        window[funcallbackname] = (renderData) => {
          this.data.theme = '' + renderData.data.theme
          if (this.init) {
            this.init = false
          }
          // 校验现在的theme是否与iframe显示的选择的theme一致
          this.$refs['iframeRender'].contentWindow.checkTheme(this.data.theme)
        }
      }
    },
    borRadiusblur () {
      if (isNaN(parseInt(this.data.config.borderRadius))) {
        this.data.config.borderRadius = 0
      } else {
        this.data.config.borderRadius = parseInt(this.data.config.borderRadius)
      }
    },
    deleteImage (index) {
      let item = this.data.imageList[index]
      if (!item) {
        return
      }
      let repertory = this.repertoryData[index]
      if (!repertory) {
        return
      }

      this.data.imageList.splice(index, 1)
      this.repertoryData.splice(index, 1)
    },
    // 拖拉排序
    datadragEnd (event) {
      let item = this.repertoryData[event.oldIndex - 1]
      this.repertoryData.splice(event.oldIndex - 1, 1)
      this.repertoryData.splice(event.newIndex - 1, 0, item)
    },
    // 编辑图片属性
    editorAttr (index) {
      let item = this.data.imageList[index]
      if (!item) {
        return
      }
      let repertory = this.repertoryData[index]
      if (!repertory) {
        return
      }

      this.$refs['wDialogImageAttr'].open({ alt: item.alt, title: item.title, caption: item.caption }, (image) => {
        this.data.imageList[index].alt = image.alt
        this.data.imageList[index].title = image.title
        this.data.imageList[index].caption = image.caption
      })
    },
    // 编辑图片的链接
    editorLink (index) {
      let item = this.data.imageList[index]
      if (!item) {
        return
      }
      let repertory = this.repertoryData[index]
      if (!repertory) {
        return
      }

      this.$refs['wDialogLink'].open(item.imglink, (link) => {
        this.data.imageList[index].imglink = link
      })
    },
    // 添加图片
    addImage () {
      if (this.data.imageList.length >= this.total) {
        this.$message.error('图片列表总数不能超过' + this.total + '张！')
        return
      }
      this.$refs['chooseImage'].show({ title: '选择图片', max: this.total - this.data.imageList.length, where: { type: [0, 4] }, fixedCondition: { type: true } }, (repertoryList) => {
        if (repertoryList.length > 0) {
          // let maxOrderNum = 0
          // if (this.repertoryData && this.repertoryData.length > 0) {
          //   this.repertoryData.forEach(element => {
          //     if (element.orderNum > maxOrderNum) {
          //       maxOrderNum = element.orderNum
          //     }
          //   })
          // }

          repertoryList.forEach(item => {
            let src = functions.getRepertoryImageSrcByHostRepertory(item)

            // let repertoryData = {
            //   id: -1,
            //   parentId: 0,
            //   type: 11,
            //   orderNum: ++maxOrderNum,
            //   config: {
            //     title: '',
            //     alt: '',
            //     caption: '',
            //     imglink: {
            //       href: '',
            //       target: ''
            //     }
            //   },
            //   repertory: item,
            //   child: null
            // }
            this.data.imageList.push({
              src: src,
              title: '',
              alt: '',
              caption: '',
              imglink: {
                href: '',
                target: ''
              }
            })
            let imghrepertory = {}
            imghrepertory.hrepertory = item
            this.repertoryData.push(imghrepertory)
          })
        }
      })
    },
    getComponentName () {
      var compname = this.iframeStyle.compname
      var temp = this.titleCase(compname.replace('_', ' ')).replace(' ', '')
      return temp.replace(temp[0], temp[0].toLowerCase())
    },
    titleCase (str) {
      return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
    },
    // ......
    close () {
      this.dialogShow = false
      this.iframeLoading = true
      this.iframeStyle = {}
      this.component = null
      this.data = null
      this.iframeSrc = ''
      this.repertoryData = []
      this.activeName = '1'
      this.init = true
      this.initiframe = true
    },
    saveclose () {
      this.bjComponent.render.data = _.cloneDeep(this.data)
      this.bjComponent._other.imageList = _.cloneDeep(this.repertoryData)
      BackendjsFunctions.saveComponent(this.bjComponent)
      this.close()
    }
  },
  components: {
    SetDesignDialog,
    PaddingTop,
    PaddingBottom,
    ChooseRepertory,
    WDialogLink,
    WDialogImageAttr,
    draggable
  }
}

const themes = [
  { theme: '1', content: '无效果' },
  { theme: '2', content: '移入右移' },
  { theme: '3', content: '移入上移' },
  { theme: '4', content: '移入旋转 360°' },
  { theme: '5', content: '移入放大' },
  { theme: '6', content: '移入缩小' },
  { theme: '7', content: '移入朦胧消失' },
  { theme: '8', content: '文字消失，图片出现' },
  { theme: '9', content: '底部透明文字' },
  { theme: '10', content: '底部文字挤压上移' },
  { theme: '11', content: '文字中间自然出现' },
  { theme: '12', content: '文字扩大出现' },
  { theme: '13', content: '左上角划入' },
  { theme: '14', content: '右上角划入' },
  { theme: '15', content: '横向转动' },
  { theme: '16', content: '纵向转动' },
  { theme: '17', content: '文字右移入+图片左移出' },
  { theme: '18', content: '文字左移入+图片右移出' },
  { theme: '19', content: '文字右移入+图片小左移' },
  { theme: '20', content: '文字左移入+图片小右移' },
  { theme: '21', content: '链接图标' },
  { theme: '22', content: '查看图标' },
  { theme: '23', content: '边框链接' },
  { theme: '24', content: '阴影扫描' },
  { theme: '25', content: '鼠标方向划入' }
]

</script>
<style scoped>
.images-edit .image-slot {
  color: #656565;
  display: flex;
  justify-content: center;
  align-items: center;
}
.edit-container-u {
  width: 840px;
  min-height:calc(100vh - 200px);
}
.imgList-u {
  height:calc(100vh - 260px);
  overflow-y: auto;
}
.theme-uu /deep/ .el-input__suffix {
  display:none;
}
</style>
